var app = getApp();
var api = require('../../utils/baiduai.js');
Page({
  data: {
    motto: '人脸检测带框选',
    result: [],
    images: {},
    img: '',
    windowWidth: 0,
    base64img: ''
  },
  onShareAppMessage: function () {
    return {
      title: '人脸检测带框选',
      path: '/pages/face/face',
      success: function (res) {
        if (res.errMsg == 'shareAppMessage:ok') {
          wx.showToast({
            title: '分享成功',
            icon: 'success',
            duration: 500
          });
        }
      },
      fail: function (res) {
        if (res.errMsg == 'shareAppMessage:fail cancel') {
          wx.showToast({
            title: '分享取消',
            icon: 'loading',
            duration: 500
          })
        }
      }
    }
  },
  clear: function (event) {
    console.info(event);
    wx.clearStorage();
  },
  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  uploads: function () {
    var that = this
    var takephonewidth
    var takephoneheight
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        wx.getImageInfo({
          src: res.tempFilePaths[0],
          success(res){
            takephonewidth = res.width,
            takephoneheight = res.height
          }
        })
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        if (res.tempFiles[0].size > (4096 * 1024)) {
          wx.showToast({
            title: '图片文件过大哦',
            icon: 'none',
            mask: true,
            duration: 1500
          })
        } else {
          wx.showLoading({
            title: "分析中...",
            mask: true
          })
          that.setData({
            img: res.tempFilePaths[0]
          })
        }
        const imageDom = wx.createSelectorQuery();
        imageDom.select('#imageDom').boundingClientRect()
        imageDom.selectViewport().scrollOffset()
        imageDom.exec(function (res) {
          // res[0].top       // #the-id节点的上边界坐标
          // res[1].scrollTop // 显示区域的竖直滚动位置
          that.setData({
            windowWidth:res[0].height*0.95
          })
        })
        //根据上传的图片读取图片的base64
        var fs = wx.getFileSystemManager();
        fs.readFile({
          filePath: res.tempFilePaths[0].toString(),
          encoding: 'base64',
          success(res) {
            //获取到图片的base64 进行请求接口
            api.faceDetectRequest(res.data, 'BASE64','age,beauty,emotion,face_type', {
              success(res) {
                console.info(res);
                  if (res.error_code === 0) {
                    wx.hideLoading();

                    res.result.face_list.forEach((item) => {
                      var emotionType = item.emotion.type;
                      if (emotionType == 'angry') {
                        item.emotion.type = '愤怒';
                      } else if (emotionType == 'disgust') {
                        item.emotion.type = '厌恶';
                      } else if (emotionType == 'fear') {
                        item.emotion.type = '恐惧';
                      } else if (emotionType == 'happy') {
                        item.emotion.type = '高兴';
                      } else if (emotionType == 'sad') {
                        item.emotion.type = '伤心';
                      } else if (emotionType == 'surprise') {
                        item.emotion.type = '惊讶';
                      } else if (emotionType == 'neutral') {
                        item.emotion.type = '无情绪';
                      } else {
                        item.emotion.type = '未知表情';
                      }
                      var faceType = item.face_type.type;
                      if (faceType =='human'){
                        item.face_type.type = '真实人脸';
                      }
                      if (faceType == 'cartoon') {
                        item.face_type.type = '卡通人脸';
                      }
                    })
                    that.setData({
                      result: res.result.face_list
                    })
                    var ctx = wx.createCanvasContext('canvas');
                    ctx.setStrokeStyle('#31859c')
                    ctx.setLineWidth(3)
                    //拿到人脸位置信息 进行画框
                    for (let j = 0; j < res.result.face_num; j++) {
                      var cavansl = res.result.face_list[j].location.left / takephonewidth * that.data.windowWidth
                      var cavanst = res.result.face_list[j].location.top / takephoneheight * that.data.windowWidth
                      var cavansw = res.result.face_list[j].location.width / takephonewidth * that.data.windowWidth
                      var cavansh = res.result.face_list[j].location.height / takephoneheight * that.data.windowWidth
                      var emotionType = res.result.face_list[j].emotion.type;
                      console.log(cavansl + '-' + cavanst + '-' + cavansw + '-' + cavansh);
                      var cavanstext = j+1;
                      ctx.setFontSize(14);
                      ctx.setFillStyle("#07C160")
                      //设置旋转角度
                      ctx.rotate(res.result.face_list[j].location.rotation * Math.PI / 180)
                      ctx.fillText(cavanstext, cavansl, cavanst - 2)
                      ctx.strokeRect(cavansl, cavanst, cavansw*0.95, cavansh*0.95)
                    }
                    ctx.draw();
                  } else {
                    wx.hideLoading();
                    var cavanstext = "未能检测到人脸";
                    var ctx = wx.createCanvasContext('canvas')
                    ctx.setFillStyle("#07C160")
                    ctx.fillText(cavanstext, 100, 100)
                    ctx.draw();
                  }
                }
            })
          }
        })
      },
    })
  },
  onLoad: function () {
  }
});